package com.atguigu.tingshu.user.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@LoginBean(1)
public class WxLogin implements ILogin{
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public Map<String, Object> login(LoginParam param) throws Exception {
          //调用微信接口,获取openId
        WxMaJscode2SessionResult sessionInfo = this.wxMaService.getUserService().getSessionInfo(param.getCode());
        String openid = sessionInfo.getOpenid();

        //根据openID查询用户信息

        UserInfo userInfo = this.userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        if (userInfo == null){
            //隐式注册用户
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友"+ IdWorker.getIdStr());
            userInfo.setAvatarUrl("https://pics0.baidu.com/feed/279759ee3d6d55fbf4d2ded878db724421a4dd3b.jpeg");
            userInfo.setIsVip(0);
            userInfo.setStatus("1");
            this.userInfoMapper.insert(userInfo);
            Long userId = userInfo.getId();

            //初始化账户信息
            this.userAccountFeignClient.saveAccount(userId);
        }
        // 生成token，并把登录状态保存在redis中
        String token = UUID.randomUUID().toString();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        this.redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX +token,userInfoVo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        //把token返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }
}
